# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase


class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Codec:
    def serialize_tree(self, root, tree_str):
        if root:
            tree_str += str(root.val) + ','
            tree_str = self.serialize_tree(root.left, tree_str)
            tree_str = self.serialize_tree(root.right, tree_str)
        else:
            tree_str += 'null,'

        return tree_str

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        return self.serialize_tree(root, "")

    def deserialize_tree(self, data_array: List[str]):
        if data_array[0] == '':
            return None
        if data_array[0] == 'null':
            data_array.pop(0)
            return None
        else:
            root = TreeNode(data_array[0])
            data_array.pop(0)
            root.left = self.deserialize_tree(data_array)
            root.right = self.deserialize_tree(data_array)
            return root

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        data_array = data.split(',')
        for item in data_array:
            item.strip()

        return self.deserialize_tree(data_array)


if __name__ == '__main__':
    codec = Codec()
    root = codec.deserialize('1,2,3,null,null,4,5,null,null,null,null,')
    data = codec.serialize(root)
    print(data)


